﻿using DotNetSpeech;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

public partial class MyRichTextBox : RichTextBox
{
    private bool boolMultiLine = true;

    public string strFilename = "";

    public MyRichTextBox()
    {
        InitializeComponent();

        Disposed += MyRichTextBox_Disposed;
        this.LinkClicked += MyRichTextBox_LinkClicked;

        

    }

    void MyRichTextBox_LinkClicked(object sender, LinkClickedEventArgs e)
    {
        System.Diagnostics.Process.Start(e.LinkText);
    }

    private void MyRichTextBox_Disposed(object sender, EventArgs e)
    {
        //throw new NotImplementedException();
        if (this.sp != null)
        {
            sp.Pause();
            sp = null;
            GC.Collect();
        }
    }

    //public MyRichTextBox(IContainer container)
    //{
    //    container.Add(this);

    //    InitializeComponent();
    //}

    /// <summary>
    /// 保存
    /// </summary>
    public void SaveDefault()
    {
        if (string.IsNullOrEmpty(strFilename)) { return; }
        FileInfo f = new FileInfo(strFilename);
        if (!f.Directory.Exists)
        {
            f.Directory.Create();
        }

        if (strFilename != "")
        {
            if (System.IO.Path.GetExtension(strFilename).ToLower().Equals(".rtf"))
                this.SaveFile(strFilename);
            else
                this.SaveFile(strFilename, RichTextBoxStreamType.PlainText);
        }
    }

    private List<int> searchResult = new List<int>();

    /// <summary>
    /// //查找
    ///
    /// </summary>
    /// <param name="searchString"></param>
    /// <param name="color"></param>
    public int searchString(string searchString, System.Drawing.Color color)
    {
        searchResult.Clear();

        this.Select(0, this.Text.Length);
        this.SelectionColor = System.Drawing.Color.Black;
        int index;

        //第一次搜索
        //index = this.Text.IndexOf(searchString);
        index = this.Find(searchString, RichTextBoxFinds.MatchCase);

        //这个标志是滚动到第一个搜索项
        int flag = index;

        while (index != -1)
        {
            this.Select(index, searchString.Length);
            this.SelectionColor = color;

            index = this.Find(searchString, index + 1, RichTextBoxFinds.MatchCase);
            //index = this.Text.IndexOf(searchString, index + 1);
            if (index != -1)
            {
                searchResult.Add(index);
            }
        }

        if (flag != -1)
        {
            this.Select(flag, searchString.Length);
        }
        //移动到插入符号
        this.ScrollToCaret();

        if (flag == -1)
        {
            return 0;
        }
        else
        {
            return searchResult.Count + 1;
        }
    }

    public void ScrollPosition()
    {
        if (searchResult.Count > 0)
        {
            //因为搜索不爽所以 code项目变化 net 得到鼠标位置 鼠标点击之后的位置开始搜索
            //滚动是下一个位置 那么现在先得到鼠标的位置，先滚动到鼠标位置
            while (this.SelectionStart > searchResult[0])
            {
                //this.Select(searchResult[0], 1);
                //this.ScrollToCaret();
                searchResult.RemoveAt(0);
            }
            this.Select(searchResult[0], 1);
            this.ScrollToCaret();
            searchResult.RemoveAt(0);
        }
        else
        {
            MessageBox.Show("已经是最后一个");
        }
    }

    public SpVoice sp;

    /// <summary>
    /// 键盘快捷键
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void SearchableRichTextBox_KeyDown(object sender, KeyEventArgs e)
    {
        //*********************************************************
        //Add
        //*********************************************************
        if (e.Modifiers == Keys.Control)
        {
            if (e.KeyCode == Keys.Q)
            {
                this.SelectionLength = 0;
                this.SelectedText = DateTime.Now.ToLongDateString();

                e.SuppressKeyPress = true; // don't pass the event down
            }
            else if (e.KeyCode == Keys.S)
            {
                SaveDefault();

                e.SuppressKeyPress = true; // don't pass the event down
            }
            else if (e.KeyCode == Keys.W)
            {
                if (boolMultiLine)
                {
                    this.Multiline = true;
                    this.RightMargin = this.Width - 50;

                    this.WordWrap = true;
                    boolMultiLine = !boolMultiLine;
                }
                else
                {
                    this.Multiline = true;
                    this.RightMargin = 100000;

                    this.WordWrap = false;
                    boolMultiLine = !boolMultiLine;
                }

                e.SuppressKeyPress = true; // don't pass the event down
            }
            else if (e.KeyCode == Keys.R)
            {
                //RunFile.run(strFilename);
                //e.SuppressKeyPress = true; // don't pass the event down
                var a = this;
                int i = a.Text.Length;
                int len = 300;
                Random r = new Random();
                if (i - 300 >= 0)
                {
                    int start = r.Next(1, i - len);
                    a.Select(start, len);
                    a.SelectionColor = Color.Red;
                    a.ScrollToCaret();
                }

                e.SuppressKeyPress = true; // don't pass the event down
            }
        }
        else if (e.KeyCode == Keys.F5)
        {
            RunFile.run(strFilename);
            e.SuppressKeyPress = true; // don't pass the event down
        }

        //else if (e.KeyCode == Keys.Tab)
        //{
        //    e.SuppressKeyPress = true; // don't pass the event down
        //}
        else if (e.KeyCode == Keys.F4)
        {
            try
            {
                if (!string.IsNullOrEmpty(this.SelectedText.Trim()))
                {
                    if (sp == null)
                        sp = new SpVoice();
                    sp.Rate = 1;

                    sp.Voice = sp.GetVoices().Item(0);

                    SpeechVoiceSpeakFlags sFlags = SpeechVoiceSpeakFlags.SVSFlagsAsync;
                    sp.Speak(this.SelectedText, sFlags);

                    e.SuppressKeyPress = true; // don't pass the event down
                }
            }
            catch (Exception)
            {
            }
        }
        else if (e.KeyCode == Keys.F3)
        {
            if (!string.IsNullOrEmpty(this.SelectedText.Trim()))
            {
                string from = "";
                string to = "";

                string str = common.translate.fanyi.GetYoudaotextStr(this.SelectedText.Trim(), from, to);
                str = "[" + str + "]";

                var mJObj = JArray.Parse(str);

                //foreach (var ss in mJObj)  //查找某个字段与值
                //{
                //    foreach (var item in ss)
                //    {
                //    }
                //}

                MessageBox.Show(mJObj.ToString());

                //JArray json = JsonConvert.DeserializeObject(str) as JArray;
                //var r=json.CreateReader();
                //foreach (var item in json)
                //{
                //}

                //MessageBox.Show(s);
            }
            e.SuppressKeyPress = true; // don't pass the event down
        }
        else if (e.KeyCode == Keys.F8)
        {
            if (!string.IsNullOrEmpty(this.SelectedText.Trim()))
            {
                //Point pos = Cursor.Position;
                //int firstIndex = this.GetCharIndexFromPosition(pos);
                //int firstLine = this.GetLineFromCharIndex(firstIndex);
                //int i = this.GetFirstCharIndexFromLine(firstLine);
                //int j = this.GetFirstCharIndexFromLine(firstLine + 1);//注意如果要选取最后一行的时候，这里可能会出错，应当直接把j设置成为最后一个字符的位置+1
                //this.Select(i, j - i); //richTextBox1.SelectedText//这里面就是这一行的值

                Process ps = new Process();
                ps.StartInfo.FileName = "iexplore.exe";
                ps.StartInfo.Arguments = this.SelectedText.Trim();
                ps.Start();
            }
            e.SuppressKeyPress = true; // don't pass the event down
        }
    }
}